export function getOneQueryByKey(name) {
  let pathName = location.pathname
  let hash = location.hash
  return getOneQueryByKeyAndStr(name, pathName) || getOneQueryByKeyAndStr(name, hash)
}

export function getOneQueryByKeyAndStr(name, str) {
  let search = ''
  if (str.indexOf('?') > -1) {
    search = str.substring(str.indexOf('?'))
  }
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  let r = search.substr(1).match(reg)
  if (r != null) return unescape(r[2])
  return null
}

export function removeQueryByKeyAndStr(name, str) {
  let splits = str.split('?')
  if (!splits[1]) {
    return str
  }
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(?=(&|$))', 'g')

  let replace = splits[1].replace(reg, '').replace(/^&/, '')
  if (replace) {
    return splits[0] + '?' + replace
  }
  return splits[0]
}

export function removeQuery(name) {
  let pathName = location.pathname
  let hash = location.hash
  let newPathName = removeQueryByKeyAndStr(name, pathName)
  let newHash = removeQueryByKeyAndStr(name, hash)
  if (newPathName !== pathName || newHash !== hash) {
    window.history.pushState(null, null, location.origin + newPathName + newHash)
  }
}
